package com.cloxtec.scada.service;

import com.alibaba.fastjson.JSONObject;
import com.cloxtec.scada.utils.ParamHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


@Component
@Slf4j
public class MsgManager {

    @Resource
    private ParamHelper paramHelper;
    @Resource
    private MqttMsgHandler msgHandler;

    private List<Object> listParserThread;
    private BlockingQueue<JSONObject> queue;
    private static int currentId = 0;

    private List<JSONObject> msgs;

    public MsgManager() {
        listParserThread = new ArrayList<Object>();
        queue = new LinkedBlockingQueue<JSONObject>();
        msgs = new ArrayList<>();
    }

    public void init() {
        int nCount = 4;
        JSONObject param = paramHelper.getParamById("param_system", "work_thread_count");
        if (param != null) {
            if (param.getIntValue("value") > 0) {
                nCount = param.getIntValue("value");
            }
        }

        for (int i = 0; i < nCount; i++) {
            MsgParserThread td = new MsgParserThread(msgHandler, this, i);
            if (td != null) {
                listParserThread.add(td);
                td.start();
            }
        }
    }

    public int addMsg(JSONObject jsonData) {
        int nCount = 0;
        if (!queue.add(jsonData)) {
            nCount = -1;
        } else {
            nCount = queue.size();
        }

//        synchronized (msgs){
//            msgs.add(jsonData);
//            nCount = msgs.size();
//        }

        return nCount;
    }

    public JSONObject getMsg() {
        JSONObject msg = null;

//        synchronized (msgs){
//            if (msgs.size() > 0){
//                msg = msgs.remove(0);
//            }
//        }

        try {
            msg = queue.take();
        } catch (InterruptedException e) {
            log.info(e.getMessage());
        }
        return msg;
    }
}
